package ltd.hxya.novel.admin.service.impl;

import ltd.hxya.novel.admin.service.CacheService;
import ltd.hxya.novel.admin.vo.Cache;
import ltd.hxya.novel.common.exception.NovelGlobalException;
import ltd.hxya.novel.common.utils.RedisUtils;
import ltd.hxya.novel.common.bean.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class CacheServiceImpl implements CacheService {
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public List<Cache> cacheNames() {
        Set<String> allKey= redisUtils.getAllKey();
        int index=0;
        List<Cache> cacheTree = getCacheTree(allKey, index);
        return cacheTree;

    }

    @Override
    public String cacheData(String key) {
        String json = redisUtils.get(key);
        if (StringUtils.isEmpty(key)){
            throw new NovelGlobalException(ResultEnum.CACHE_DELETE.getCode(), ResultEnum.CACHE_DELETE.getMsg());
        }
        return json;
    }

    @Override
    public void deleteKey(String key) {
        redisUtils.delete(key);
    }

    @Override
    public void clearCache() {
        redisUtils.clearCache();
    }

    private List<Cache> getCacheTree(Set<String> allKey,int index) {
        Map<String,Object> cacheMap = new LinkedHashMap<>();

        allKey.stream().forEach(key -> {
            String[] strings = key.split(":");
            if (index<strings.length-1){
                Set<String> keys = (Set<String>) cacheMap.get(strings[index]);
                if (CollectionUtils.isEmpty(keys)){
                    keys = new HashSet<String>();
                }
                keys.add(key);

                cacheMap.put(strings[index],keys);

            }
            if (index==strings.length-1){
                cacheMap.put(strings[index],key);
            }


        });

        List<Cache> cacheList = new ArrayList<>();
        cacheMap.forEach((key,value)->{
            Cache cache = new Cache();
            cache.setName(key);
            if (!(value instanceof String)){
                cache.setChildren(getCacheTree((Set<String>) value,index+1));

            }else {
                cache.setKey((String) value);
            }
            cacheList.add(cache);

        });
        return cacheList;
    }


    //判断是否相等
}
